
import { S3Client } from '@aws-sdk/client-s3';
import { DependencyContainer } from 'tsyringe'
import { ROOT } from '@sker/core'
import { useAddonSetting } from '@sker/runtime'
import { join } from 'path';

export const createS3 = async <T>(injector: DependencyContainer, callback: (ds: S3Client, config: any) => Promise<T>) => {
    const root = injector.resolve(ROOT)
    const env = injector.resolve<any>('ENV')
    let config: any = {
        apiVersion: env.S3_API_VERSION,
        region: env.S3_REGION,
        endpoint: env.S3_ENDPOINT,
        accessKeyId: env.S3_ACCESS_KEY,
        secretAccessKey: env.S3_SECRET_KEY,
        publicBucket: env.S3_PUBLIC_BUCKET,
        privateBucket: env.S3_BUCKET
    }
    let s3Setting = await useAddonSetting('@imeepos/s3')
    if (s3Setting) {
        config = {
            config,
            ...s3Setting
        }
    }
    if (!config) {
        const jsonFile = join(`${root}`, 'data/plugins', `@sker/s3.json`)
        config = require(jsonFile)
    }
    const s3Config = {
        apiVersion: config.apiVersion,
        region: config.region,
        endpoint: config.endpoint,
        credentials: {
            accessKeyId: config.accessKeyId,
            secretAccessKey: config.secretAccessKey
        }
    }
    const client = new S3Client({
        ...s3Config,
        forcePathStyle: true
    });
    const res = await callback(client, config)
    client.destroy();
    return res;
}

export default createS3;
